/**
 * 获取元素尺寸（width、height）
 * @param elementRef 元素ref
 * @returns 元素尺寸size 不包含padding和border
 */

import { useEffect, useState } from 'react'

export const useElementSize = (elementRef: React.RefObject<HTMLElement>) => {
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)
  useEffect(() => {
    const element = elementRef.current

    if (!element) {
      console.error('useElementSize 元素获取失败')
      return
    }

    const resizeObserver = new ResizeObserver((entries) => {
      const { width, height } = entries[0].contentRect
      setWidth(width)
      setHeight(height)
    })
    resizeObserver.observe(element)
    return () => {
      resizeObserver.disconnect()
    }
  }, [])

  return { width, height, setWidth, setHeight }
}
